<template>
  <div>
    <el-row>
      <el-col :span="18">
        <el-form ref="form" :model="query" label-width="80px" :inline="true">
          <el-form-item label="截止日期">
            <el-date-picker
              v-model="query.startdate"
              placeholder="截止日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearch()">搜索</el-button>
          </el-form-item>
        </el-form>

        <linechart :options="options" />
        <linechart :options="options2" />
        <linechart :options="options3" />

      </el-col>
      <el-col :span="6">
        <h2>设备信息</h2>
        <el-descriptions
          title="基本信息"
          direction="vertical"
          :column="2"
          border
        >
          <el-descriptions-item label="设备名称">{{
            device.title
          }}</el-descriptions-item>
          <el-descriptions-item label="设备ID">{{
            device.deviceid
          }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            {{ parseInt(device.clientid) ? '在线' : '离线' }}
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions
          title="所属项目"
          direction="vertical"
          :column="2"
          border
          v-if="project"
        >
          <el-descriptions-item label="项目名称">{{
            project.username
          }}</el-descriptions-item>
          <el-descriptions-item label="项目公司">{{
            project.project_company
          }}</el-descriptions-item>
          <el-descriptions-item label="管理员姓名">{{
            project.manager_name
          }}</el-descriptions-item>
          <el-descriptions-item label="管理员电话" :span="1">{{
            project.manager_tel
          }}</el-descriptions-item>
          <el-descriptions-item label="所在区域">{{
            project.area
          }}</el-descriptions-item>
          <el-descriptions-item label="详细地址">{{
            project.project_address
          }}</el-descriptions-item>
        </el-descriptions>

        <el-descriptions
          title="用电统计"
          direction="vertical"
          :column="2"
          border
        >
          <el-descriptions-item label="最近7天累计用电量">{{
            weekElectricity ? weekElectricity : 0
          }}</el-descriptions-item>
          <el-descriptions-item :label="month + '月累计用电量'">
            {{ monthElectricity ? monthElectricity : 0 }}
          </el-descriptions-item>
          <el-descriptions-item label="历史累计总用电量">
            {{ totalElectricity ? totalElectricity : 0 }}
          </el-descriptions-item>
        </el-descriptions>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { statistics } from '@/api/equipment/index.js';
import moment from 'moment';
import linechart from '@/views/chart/components/linechart';

export default {
  components:{
    linechart
  },
  props: ['deviceid'],
  watch: {
    deviceid: {
      handler: function (val) {
        this.query.deviceid = val;
        this.query.startdate = moment().format('YYYY-MM-DD');
        this.getData();
        //setTimeout() 如果要定时更新直接在这里定时getData就行了。 原来是十分钟一次，感觉完全没有必要，重新打开一下就行。
      },
      immediate: true,
    },
  },
  data() {
    return {
      query: {
        startdate: moment().format('YYYY-MM-DD'), //截至日期搞什么startdate
        deviceid: '',
        ln: '',
      },
      data: '',
      device: {},
      lnidArr: {},
      minutes: [],
      month: '',
      monthElectricity: 0,
      project: {},
      startdate: '',
      time: '',
      totalElectricity: '',
      weekElectricity: '',

      options:{},
      options2:{},
      options3:{}
    };
  },
  methods: {
    getData() {
      statistics(this.query).then((res) => {
        console.log('tongji', res);
        this.data = JSON.parse(res.data.data);
        this.device = res.data.device;
        this.lnidArr = JSON.parse(res.data.lnidArr);
        this.minutes = JSON.parse(res.data.minutes);
        this.month = res.data.month;
        this.monthElectricity = res.data.monthElectricity;
        this.project = res.data.project;
        this.startdate = res.data.startdate;
        this.time = res.data.time;
        this.totalElectricity = res.data.totalElectricity;
        this.weekElectricity = res.data.weekElectricity;
        this.initChartData();
      });
    },
    onSearch() {      
      this.getData()
    },
    initChartData() {
      console.log(this.minutes,'是这个吗');
      this.minutes.pop();//去掉最后一个，因为这个时间有可能没到，然后显示数据为0，看起来像错误。
      this.minutes.unshift('时间');
      console.log(this.minutes);
      console.log(this.data);
      let data = this.getTempCurrent(this.data, this.minutes);

      //获取温度、电流统计
      let tempData = data.temp;
      let currentData = data.current;
      let voltageData = data.voltage;
      // 图例
      let series = [];
      // 图例 选中状态
      let selected = [];
      let bool = true;
      Object.keys(this.lnidArr).forEach(function (key) {
        // 选中状态（默认只显示第一个）
        selected[key] = bool;
        bool ? (bool = false) : null;
        series.push({ name: key, type: 'line', seriesLayoutBy: 'row' });
      });
      console.log(series,'series');

      let option = {
            title: {
                text: '温度K线图',
                //subtext: `更新至：${formatTime2Date(time)} (每${unit}分钟更新一次)`,
                left: 'center',
                paddingBottom: 5,
                textStyle: {fontWeight: 'normal', fontSize: 10}
            },
            legend: {
                type: 'scroll',
                orient: 'vertical',
                left: 0,
                top: 0,
                bottom: 5,
                formatter: '{name}路',
                data: series,
                //selected
            },
            dataset: {
                source: tempData
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                name: "时间"
            },
            yAxis: {gridIndex: 0, name: "温度(℃)"},
            series
        };
    
        this.options = option;
        //let tmpKeys = Object.keys(this.options)
        
        let optionstr = JSON.stringify(option)
        
        this.options2 = JSON.parse(optionstr)
        this.options2.title.text = '电流K线图';
        this.options2.yAxis.name = '电流(A)';
        this.options2.dataset.source = currentData;
        
        this.options3 = JSON.parse(optionstr)
        this.options3.title.text = '电压K线图';
        this.options3.yAxis.name = '电压(V)';
        this.options3.dataset.source = voltageData;
        
    },
    //获取温度、电流统计
    getTempCurrent(data, minutes) {
      let temp = {};
      let current = {};
      let voltage = {};
      //遍历所有分路的统计
      Object.keys(data).forEach(function (datetime) {
        const item = data[datetime];
        Object.keys(item).forEach(function (ln) {
          //第一列 赋初始值
          if (
            typeof temp[ln] == 'undefined' &&
            typeof current[ln] == 'undefined' &&
            typeof voltage[ln] == 'undefined'
          ) {
            temp[ln] = [ln + '路'];
            current[ln] = [ln + '路'];
            voltage[ln] = [ln + '路'];
          }
          temp[ln].push(item[ln]['temp']);
          current[ln].push(item[ln]['current']);
          voltage[ln].push(item[ln]['voltage']);
        });
      });
      let result = { temp: [minutes], current: [minutes], voltage: [minutes] };
      //温度
      Object.values(temp).forEach(function (item) {
        result.temp.push(item);
      });
      //电流
      Object.values(current).forEach(function (item) {
        result.current.push(item);
      });
      //电压
      Object.values(voltage).forEach(function (item) {
        result.voltage.push(item);
      });

      return result;
    },
  },
};
</script>

<style scoped></style>
